<?php
/**
 * Created by PhpStorm.
 * User: xiaomage
 * Date: 2020/12/14
 * Time: 11:35
 */

namespace common;

use think\Exception;
use think\exception\ValidateException;

class LogicException
{
    protected static $instance = null;

    /**
     * @var Exception
     */
    private $exception = null;

    protected function __construct()
    {

    }

    protected function __clone()
    {

    }

    /**
     * @return LogicException|null
     */
    public static function instance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * @param null $exception
     * @return null
     */
    public function exception($exception = null)
    {
        if ($exception) {
            $this->exception = $exception;
        }

        return $this->exception;
    }

    /**
     * @return array
     */
    public function api()
    {
        $message = '';
        $code = 1;
        if ($this->exception) {
            if ($this->exception instanceof ValidateException) {
                $code = -10010;
            }
            $message = $this->exception->getMessage() ?? '';
        }

        return [
            'code' => $code,
            'msg' => $message,
            'data' => null
        ];
    }
}